package com.laviedesfons.mavenjhmtascplugin;

import com.laviedesfons.jhmtasc.cadmium.MInterpreter;
import java.io.*;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugin.MojoExecutionException;

/**
 * Make the call to the ocaml bytecode with cadmium.
 * Both are declared as maven dependencies...
 *
 * maven cookbook URL:
 * http://docs.codehaus.org/display/MAVENUSER/Mojo+Developer+Cookbook
 *
 * @goal compile-as-classes
 * @author Romano
 */
public class CompileMojo extends ParentMojo {

    private File getArtifact(String groupId, String artifactId)
            throws FileNotFoundException {

        for (Artifact a : pluginArtifacts) {
            if (a.getGroupId().equals(groupId)
                    && a.getArtifactId().equals(artifactId)) {
                return a.getFile();
            }
        }
        return null;
    }

    public InputStream getInputStreamFromZipFile(ZipFile zip, String fileToExtract) {
        Enumeration entries;
        InputStream streamFromZip = null;

//        log("***** getInputStreamFromZipFile : " + fileToExtract + "*****");
        try {
            entries = zip.entries();

            while (entries.hasMoreElements()) {

                ZipEntry entry = (ZipEntry) entries.nextElement();
                if (entry.getName().equals(fileToExtract)) {
                    streamFromZip = new BufferedInputStream(zip.getInputStream(entry));
//                    log("Extracting file : " + entry.getName());
                }
            }
        } catch (IOException ioe) {
            getLog().error(ioe);
        } finally {
            return streamFromZip;
        }
    }

    private InputStream initMojo() throws FileNotFoundException, ZipException, IOException{
        // TODO: retrieve by classpath instead...
        File mtascByteJarFile =
                getArtifact("com.laviedesfons.mtasc", "bytecode");
        ZipFile bytejarFile = new ZipFile(mtascByteJarFile);

        return getInputStreamFromZipFile(bytejarFile, "mtasc-byte");
    }

    private File[] retrieveSourceFiles(){
        return new File(sourceDir).listFiles(
                new CustomFileFilter(new String[] {"as","as2"}));
    }

    @Override
    public void execute() throws MojoExecutionException {
        try {
            // retrieve mtasc byte
            InputStream bcStream = initMojo();
            File outputDirFile = new File(outputDir);

            String args[]=null,localArgs[] = {
                "",
                "-cp",
                outputDir + "/classes/std/",
                ""
            };

            if (debug) {
                args = new String[localArgs.length + 1];
                localArgs[0] = "-v";
                args[0] = "--backtrace=on";
                System.arraycopy(localArgs, 0, args, 1, localArgs.length);

                // display for debug
                getLog().info("args...");
                for(String s : args){
                    if(s.isEmpty())
                        getLog().info("EMPTY");
                    else
                        getLog().info(s);
                }
            } else {
                args = localArgs;
            }

            if (outputDirFile.mkdirs() || outputDirFile.exists()) {
                //TODO handle exception and return codes for compilation failures

                for(File asFile : retrieveSourceFiles()){
                    args[args.length-1] = asFile.getPath();
                    MInterpreter.execute(bcStream, args, new MavenLogger(getLog()));
                }
            }
        } catch (IOException ex) {
            getLog().error(ex);
        }
    }
}

// TODO: CLEANER TOUS LES OUTPUTS
// TODO: ADD LOGGING LEVELS, LIKE INFO DEBUG ETC...
// TODO: SUPPRIMER LE PROBLEME D'ENCODAGE AU BUILD MAVEN